<?php

/*
	PIE Content Management System
	John Girata
	Licensed under the GNU General Public License version 3
*/

defined('PIESECVAR') or die('Restricted Access');

class DatabaseHandler
{
	private $con; // Connection ID
	private $result = '';
	private $error = '';
	var $num_queries = 0;
	
	function __construct()
	{
		global $params;
		
		$this->con = $this->db_connect($params->db_host, $params->db_username, $params->db_password, $params->db_database);
		
		if(!$this->con)
			die('Cannot connect to the database.');
	}
	
	function db_connect($host, $username, $password, $database)
	{
		if(!mysql_connect($host, $username, $password))
			return false;
		if(!mysql_select_db($database))
			return false;
		
		return true;
	}
	
	function query($query)
	{
		$this->num_queries++;
		
		global $params; // Reference to the global $params object
		
		// If we are passed an empty parameter return true
		if(empty($query))
			return true;
		
		// Replace the #__ with the table prefix
		$query = preg_replace('/#__/', $params->db_prefix, $query);
		
		$this->result = mysql_query($query);
		$this->error = mysql_error();
		
		if($this->error)
			return false;
		return true;
	}
	
	function get_num_rows()
	{
		// Cannot get the number of rows if we don't have a resource
		if(strlen($this->error) == 0)
			return mysql_num_rows($this->result);
		else
			return false;
	}
	
	function get_array($type='assoc')
	{
		$m_array = Array();
		$row;
		
		while($row = call_user_func_array("mysql_fetch_$type", Array($this->result)))
		{
			array_push($m_array, $row);
		}
		
		return $m_array;
	}
	
	function get_error()
	{
		return $this->error;
	}
	
	function escape($variable)
	{
		return mysql_real_escape_string($variable);
	}
	
	function rescape(&$variable)
	{
		$variable = mysql_real_escape_string($variable);
	}
}

?>